<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
/**
 * 门店商品管理
 * @package app\erp\admin
 */
class StoreGoods extends Admin
{
	/**
     * 门店商品列表
     * @author Naruto
     * @return mixed
     */
    public function index(){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		// 获取筛选
        $map_arr = $this->getMap();
		$store_id = '';
		foreach($map_arr as $key => $value){
			if($value[0] == 'store_id'){
				$store_id = $value[2];
				unset($map_arr[$key]);
			}
		}

		foreach ($map_arr as $key => $value) {//根据 单品得条形码 查询出 商品
			if($value[0] == 'goods_code'){
				//unset($map[$key]);
				//查询出单品得数据
				$map_1 = [];
				$map_1[] = ['article_no', 'like', '%'.$value[2].'%'];
				$rel = model('ErpGoodsSku') -> where($map_1) -> column('goods_id');

				$map_arr[$key] = [
					'id',
					'in',
					$rel,
				];
			}
		}
		
		$map_arr = array_values($map_arr);
		
		$map = [];
		//数据获取
        $data = input();
		
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		if($sotre_user['store_uid'] > 0){
			$map = [];
			$map['id'] = $sotre_user['store_id'];
		}

		$store_list = model('ErpStore') -> where($map) -> column('id,title');//获取列表
		if($store_id == ''){
			$store_id = key($store_list);
		}
		$store_warehouse_list =[];
		$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
		foreach ($warehouse_list['data'] as $key => $value) {
			if($value['type'] == 1){//分店仓库
				$store_warehouse_list[] = $value['wid'];
			}
		}
		
		$map = [];
		$map[] = ['warehouse_id', 'in', $store_warehouse_list];
		$warehouse_goods = model('ErpGoodsWarehouseStockNum') -> group('goods_id') -> where($map) -> column('goods_id');
		
		// 数据列表
		$map_arr[] = ['id', 'in', $warehouse_goods];
		$map_arr[] = ['goods_status', '=', 0];
		$data_list = model('erp/ErpGoods', 'model') -> where($map_arr) -> order('create_time desc') -> paginate();
		
		$btn_goods_sku = [
			'title' => '单品列表',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('goods_sku', ['goods_id' => '__id__', 'store_id' => $store_id]),
		];
		
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('门店商品列表') // 设置页面标题
            // ->setTableName('erp_store') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', 'id'],
                ['goods_name', '商品名称'],
				//['goods_code', '商品编码'],
				['unit_measurement', '计量单位'],
				['is_single_specification', '是否统一规格', ['否', '是']],
                ['right_button', '操作', 'btn']
            ])
			->setSearchArea([
                ['select', 'store_id', '选择门店', '', $store_id,  $store_list],
				['text', 'goods_name', '商品名称', 'like'],
				['text', 'goods_code', '国际条形码', 'like'],
				/*['daterange', 'create_time', '创建时间'],*/
            ])
            // ->addTopSelect('store_id', $store_title, $store_list, $store_id)
			->addRightButton('sku', $btn_goods_sku, true) // 批量添加右侧按钮
			->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
	}
	
	/**
     * 门店单品列表
     * @author Naruto
     * @return mixed
     */
    public function goods_sku($goods_id = '', $store_id = ''){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		// 数据列表
		$map = [];
		$map[] = ['goods_id', '=', $goods_id];
		
		$btn_update_price = [
			'title' => '编辑',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('update_sku', ['sku_id' => '__id__','store_id' => $store_id]),
		];
		
		$data_list = model('ErpGoodsSku') -> where($map) -> order('create_time desc') -> paginate();
		
		$store_warehouse_list = [];
		$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
		foreach ($warehouse_list['data'] as $key => $value) {
			if($value['type'] == 1){//分店仓库
				$store_warehouse_list[] = $value['wid'];
			}
		}

		foreach($data_list as $key => $value){
			$map = [];
			$map[] = ['warehouse_id', '=', $store_warehouse_list[0]]; 
			$map[] = ['sku_id', '=', $value['id']];
			$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('sum(stock_num) as stock_num,sum(frozen_num) as frozen_num,sum(available_num) as available_num,min(price) as price')->where($map)->find();//库存
			$stock_info = model('ErpGoodsWarehouseStockNum') -> where($map) -> find();
			
			// $data_list[$key]['goods_specifications'] 	= $value['goods_specifications'] == '' ? $value['goods_name'] : $value['goods_specifications'];
			$data_list[$key]['available_num'] 			= isset($goods_stock['available_num']) ? $goods_stock['available_num'] : 0 ;
			$data_list[$key]['price'] 					= isset($goods_stock['price']) ? $goods_stock['price'] : 0 ;
			$data_list[$key]['sku_status'] 				= !empty($stock_info['sku_status']) ? $stock_info['sku_status'] : 2;
			
			if(!isset($goods_stock['available_num']) && !isset($goods_stock['price'])){
				unset($data_list[$key]);
			}
		}
		
        return ZBuilder::make('table')
            ->setPageTitle('规格列表') // 设置页面标题
            // ->setTableName('erp_goods_warehouse_stock_num') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '规格id'],
                ['goods_specifications', '规格名称'],
                ['price', '单价'],
                ['available_num', '可用库存'],
				['article_no', '国际条形码'],
				// ['weight', '重量'],
				// ['volume', '体积'],
				['sku_status', '是否可售', [1 => '可销售', 2 => '不可销售']],
				['right_button', '操作', 'btn']
            ])
			->setRowList($data_list) // 设置表格数据
			->addRightButton('sku', $btn_update_price, true) // 批量添加右侧按钮
            ->fetch(); // 渲染页面
	}
	
	/**
     * 编辑
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function update_sku($sku_id = '', $store_id = ''){   
		if ($sku_id === '') $this->error('缺少参数');
		// 保存数据
		if ($this->request->isPost()) {
			$data = $this->request->post('', null, 'trim');
			$price 		= isset($data['price']) ? $data['price'] : '';
			$sku_status = isset($data['sku_status']) ? $data['sku_status'] : '';
			if($price == ''){
				$this->error('价格不能为空');
			}
			
			// $sku_id = model('ErpGoodsWarehouseStockNum') -> find($id) -> sku_id;//库存
			$rel = controller('Storelogic', 'logic') -> update_sku_price(UID, $store_id, $sku_id, $price, $sku_status);
			if($rel['code'] == 200){
				$this->success('更新成功', '', '_parent_reload');
			}else{
				$this->error($rel['message']);
			}

		}
		
		$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
		foreach ($warehouse_list['data'] as $key => $value) {
			if($value['type'] == 1){//分店仓库
				$store_warehouse_list[] = $value['wid'];
			}
		}
		
		$map = [];
		$map[] = ['warehouse_id', '=', $store_warehouse_list[0]]; 
		$map[] = ['sku_id', '=', $sku_id];

		$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('sku_status, price') -> where($map) -> find();//库存
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('更新门店价格')
            ->addFormItems([
				['text', 'price', '门店价格', '', $goods_stock['price']],
				['select', 'sku_status', '是否可售', '', [1 => '可销售', 2 => '不可销售'], $goods_stock['sku_status']],
            ])
            ->fetch();
    }
}

